package cn.btks.resultintegration.statics.service.impl;

import cn.btks.commonserver.result.ResultState;
import cn.btks.commonserver.result.StateInfo;
import cn.btks.commonserver.util.JwtUtil;
import cn.btks.resultintegration.achievements.repository.AchievementsRepository;
import cn.btks.resultintegration.achievements.repository.EnvironmentAttributeRepository;
import cn.btks.resultintegration.catalog.pojo.Catalog;
import cn.btks.resultintegration.catalog.service.CatalogService;
import cn.btks.resultintegration.feign.FeignClient.BackManageClient;
import cn.btks.resultintegration.feign.FeignObject.City;
import cn.btks.resultintegration.feign.FeignObject.County;
import cn.btks.resultintegration.feign.FeignObject.Unit;
import cn.btks.resultintegration.statics.service.StaticsService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import io.jsonwebtoken.Claims;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author lijun
 * @Date 2021/2/4 9:55
 */
@Service
public class StaticsServiceImpl implements StaticsService {

    @Autowired
    EnvironmentAttributeRepository environmentAttributeRepository;

    @Autowired
    AchievementsRepository achievementsRepository;

    @Autowired
    CatalogService catalogService;

    @Autowired
    BackManageClient backManageClient;

    @Override
    public Map<String, Object> queryUnitAreaAndCount() {
        Catalog firstCatalog = catalogService.findByKeyCode("1");
        Catalog secondCatalog = catalogService.findByKeyCode("2");
        Catalog thirdCatalog = catalogService.findByKeyCode("3");
        Map<String, Object> map = environmentAttributeRepository.queryUnitAreaAndCount(firstCatalog.getId(), secondCatalog.getId(), thirdCatalog.getId());
        Map<String,Object> newMap = new HashMap<>(map);
        double firstArea =(double) newMap.get("firstArea");
        double secondArea =(double) newMap.get("secondArea");
        double thirdArea =(double) newMap.get("thirdArea");
        firstArea = (double) Math.round(firstArea * 100) / 100;
        secondArea = (double) Math.round(secondArea * 100) / 100;
        thirdArea = (double) Math.round(thirdArea * 100) / 100;
        newMap.put("firstArea",firstArea);
        newMap.put("secondArea",secondArea);
        newMap.put("thirdArea",thirdArea);
        return newMap;
    }

    @Override
    public List<Map<String, Object>> queryCityUnitCount() {
        Catalog firstCatalog = catalogService.findByKeyCode("1");
        Catalog secondCatalog = catalogService.findByKeyCode("2");
        Catalog thirdCatalog = catalogService.findByKeyCode("3");
        List<Map<String, Object>> mapList = environmentAttributeRepository.queryCityUnitCount(firstCatalog.getId(), secondCatalog.getId(), thirdCatalog.getId());
        List<Map<String, Object>> result = new ArrayList<>();
        ResultState resultState = backManageClient.findAllCity();
        if(resultState.getData() != null){
            List<City> cityList = new ArrayList<>();
            Object data = resultState.getData();
            cityList = JSONArray.parseArray(JSON.toJSONString(data), City.class);
            List<City> collect = cityList.stream().filter(s -> s.getIsShow().equals(1)).collect(Collectors.toList());
            for (City cityItem : collect){
                if(cityItem.getCode().equals("65")){
                    continue;
                }
                Integer firstCount = 0;
                Integer secondCount = 0;
                Integer thirdCount = 0;
                //代管团场
                ResultState resultState2 = backManageClient.findAllByEscrowId(cityItem.getId());
                if (resultState2.getData() != null) {
                    Object data1 = resultState2.getData();
                    List<County> countyList = JSONArray.parseArray(JSON.toJSONString(data1), County.class);
                    if (countyList != null && countyList.size() > 0) {
                        for (County countyItem : countyList) {
                            Map<String, Object> countyMap = environmentAttributeRepository.queryCountyUnitAreaAndCount(countyItem.getName(), firstCatalog.getId(), secondCatalog.getId(), thirdCatalog.getId());
                            if (MapUtils.isNotEmpty(countyMap)) {
                                firstCount += Integer.valueOf(countyMap.get("firstCount").toString());
                                secondCount += Integer.valueOf(countyMap.get("secondCount").toString());
                                thirdCount += Integer.valueOf(countyMap.get("thirdCount").toString());
                            }
                        }
                    }
                }
                Optional<Map<String, Object>> optional = mapList.stream().filter(s -> s.get("city").equals(cityItem.getName())).findFirst();
                if(optional.isPresent()){
                    Map<String, Object> map = optional.get();
                    Map<String, Object> newMap = new HashMap<>(map);
                    newMap.put("firstCount",Integer.valueOf(map.get("firstCount").toString()) + firstCount);
                    newMap.put("secondCount",Integer.valueOf(map.get("secondCount").toString()) + secondCount);
                    newMap.put("thirdCount",Integer.valueOf(map.get("thirdCount").toString()) + thirdCount);
                    result.add(newMap);
                }else {
                    Map<String, Object> map = new HashMap<>();
                    map.put("city",cityItem.getName());
                    map.put("firstCount",firstCount);
                    map.put("secondCount",secondCount);
                    map.put("thirdCount",thirdCount);
                    result.add(map);
                }
            }
        }
        return result;
    }

    @Override
    public Map<String, Object> queryCityUnitAreaAndCount(String city) {
        Double firstArea = 0.0;
        Double secondArea =0.0;
        Double thirdArea =0.0;
        Integer firstCount =0;
        Integer secondCount = 0;
        Integer thirdCount = 0;
        Catalog firstCatalog = catalogService.findByKeyCode("1");
        Catalog secondCatalog = catalogService.findByKeyCode("2");
        Catalog thirdCatalog = catalogService.findByKeyCode("3");
        Map<String, Object> map = environmentAttributeRepository.queryCityUnitAreaAndCount(city,firstCatalog.getId(), secondCatalog.getId(), thirdCatalog.getId());
        Map<String,Object> newMap = new HashMap<>(map);
        if(MapUtils.isNotEmpty(newMap)){
            firstArea = newMap.get("firstArea") == null ? 0.0 : Double.valueOf(newMap.get("firstArea").toString());
            secondArea = newMap.get("secondArea") == null ? 0.0 : Double.valueOf(newMap.get("secondArea").toString());
            thirdArea = newMap.get("thirdArea") == null ? 0.0 : Double.valueOf(newMap.get("thirdArea").toString());
            firstCount = newMap.get("firstCount") == null ? 0 : Integer.valueOf(map.get("firstCount").toString());
            secondCount = newMap.get("secondCount") == null ? 0 : Integer.valueOf(map.get("secondCount").toString());
            thirdCount = newMap.get("thirdCount") == null ? 0 : Integer.valueOf(map.get("thirdCount").toString());
        }

        //代管团场
        ResultState resultState = backManageClient.findByCityName(city);
        if(resultState.getData() != null) {
            Object data = resultState.getData();
            City city1 = JSONArray.parseObject(JSON.toJSONString(data), City.class);
            if (city1 != null) {
                //代管团场
                ResultState resultState2 = backManageClient.findAllByEscrowId(city1.getId());
                if (resultState2.getData() != null) {
                    Object data1 = resultState2.getData();
                    List<County> countyList = JSONArray.parseArray(JSON.toJSONString(data1), County.class);
                    if (countyList != null && countyList.size() > 0) {
                        for (County countyItem : countyList) {
                            Map<String, Object> countyMap = environmentAttributeRepository.queryCountyUnitAreaAndCount(countyItem.getName(), firstCatalog.getId(), secondCatalog.getId(), thirdCatalog.getId());
                            if (MapUtils.isNotEmpty(countyMap)) {
                                firstArea += countyMap.get("firstArea") == null ? 0.0 : Double.valueOf(countyMap.get("firstArea").toString());
                                secondArea += countyMap.get("secondArea") == null ? 0.0 : Double.valueOf(countyMap.get("secondArea").toString());
                                thirdArea += countyMap.get("thirdArea") == null ? 0.0 : Double.valueOf(countyMap.get("thirdArea").toString());
                                firstCount += countyMap.get("firstCount") == null ? 0 : Integer.valueOf(countyMap.get("firstCount").toString());
                                secondCount += countyMap.get("secondCount") == null ? 0 : Integer.valueOf(countyMap.get("secondCount").toString());
                                thirdCount += countyMap.get("thirdCount") == null ? 0 : Integer.valueOf(countyMap.get("thirdCount").toString());
                            }
                        }
                    }
                }
            }
        }
        firstArea = (double) Math.round(firstArea * 100) / 100;
        secondArea = (double) Math.round(secondArea * 100) / 100;
        thirdArea = (double) Math.round(thirdArea * 100) / 100;
        newMap.put("firstArea",firstArea);
        newMap.put("secondArea",secondArea);
        newMap.put("thirdArea",thirdArea);
        newMap.put("firstCount",firstCount);
        newMap.put("secondCount",secondCount);
        newMap.put("thirdCount",thirdCount);

        return newMap;
    }

    @Override
    public List<Map<String, Object>> queryCountyUnitCount(String city) {
        Catalog firstCatalog = catalogService.findByKeyCode("1");
        Catalog secondCatalog = catalogService.findByKeyCode("2");
        Catalog thirdCatalog = catalogService.findByKeyCode("3");
        List<Map<String, Object>> result = new ArrayList<>();
        List<Map<String, Object>> mapList = environmentAttributeRepository.queryCountyUnitCount(city, firstCatalog.getId(), secondCatalog.getId(), thirdCatalog.getId());
        ResultState resultState = backManageClient.findByCityName(city);
        if(resultState.getData() != null){
            Object data = resultState.getData();
            City city1 = JSONArray.parseObject(JSON.toJSONString(data), City.class);
            if(city1 != null){
                //普通团场
                ResultState resultState1 = backManageClient.findAllByCityId(city1.getId());
                if(resultState1.getData() != null){
                    List<County> countyList = new ArrayList<>();
                    Object data1 = resultState1.getData();
                    countyList = JSONArray.parseArray(JSON.toJSONString(data1), County.class);
                    for (County countyItem : countyList){
                        Optional<Map<String, Object>> optional = mapList.stream().filter(s -> s.get("county").equals(countyItem.getName())).findFirst();
                        if(optional.isPresent()){
                            result.add(optional.get());
                        }else {
                            Map<String, Object> map = new HashMap<>();
                            map.put("city",city1.getName());
                            map.put("county",countyItem.getName());
                            map.put("firstCount",0);
                            map.put("secondCount",0);
                            map.put("thirdCount",0);
                            result.add(map);
                        }
                    }
                }
                //代管团场
                ResultState resultState2 = backManageClient.findAllByEscrowId(city1.getId());
                if(resultState2.getData() != null){
                    Object data1 = resultState2.getData();
                    List<County> countyList = JSONArray.parseArray(JSON.toJSONString(data1), County.class);
                    if(countyList != null && countyList.size() > 0){
                        for (County countyItem : countyList){
                            List<Map<String, Object>> mapList1 = environmentAttributeRepository.queryCountyUnitCountOnly(countyItem.getName(), firstCatalog.getId(), secondCatalog.getId(), thirdCatalog.getId());
                            if(mapList1 != null && mapList1.size() > 0){
                                List<Map<String, Object>> mapListTemp = new ArrayList<>();
                                for(Map<String, Object> item : mapList1){
                                    Map<String,Object> mapTemp = new HashMap<>();
                                    String countyName = item.get("county").toString();
                                    String firstCount = item.get("firstCount").toString();
                                    String secondCount = item.get("secondCount").toString();
                                    String thirdCount = item.get("thirdCount").toString();
                                    mapTemp.put("firstCount",firstCount);
                                    mapTemp.put("secondCount",secondCount);
                                    mapTemp.put("thirdCount",thirdCount);
                                    countyName+="(代管)";
                                    mapTemp.put("county",countyName);
                                    mapListTemp.add(mapTemp);
                                }
                                result.addAll(mapListTemp);
                            }
                        }
                    }
                }
            }
        }
        return result;
    }

    @Override
    public Map<String, Object> queryAchievementCountAndTime(Long cityId, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        Optional<Claims> optional = JwtUtil.getClaimsFromToken(token, JwtUtil.jwtsSecret);
        if(optional.isPresent()){
            Claims claims = optional.get();
            Object obj = claims.get("unit");
            Unit unit = JSONArray.parseObject(JSON.toJSONString(obj), Unit.class);
            if(unit != null){
                if(unit.getCityCode().equals("65")){
                    List<Map<String, Object>> mapList = achievementsRepository.queryAchievementCountAndTime(cityId);
                    if(mapList != null && mapList.size() > 0){
                        return mapList.get(0);
                    }
                }else {
                    List<Map<String, Object>> mapList = achievementsRepository.queryAchievementTempCountAndTime(unit.getCityId());
                    if(mapList != null && mapList.size() > 0){
                        return mapList.get(0);
                    }
                }
            }
        }
        return null;
    }
}
